<template>
  <div class="container">
    <canvas v-for="page in pages" :id="id+'_canvas_'+page" :key="page" class="canvas">
    </canvas>
  </div>
</template>

<script>
const PDFJS = require('pdfjs-dist')
const workerSrc = require('pdfjs-dist/build/pdf.worker.entry')
PDFJS.workerSrc = workerSrc

export default {
  name: 'pdf-canvas',
  props: {
    linkUrl: {
      type: String,
      default: '',
      require: true
    },
    scale: {
      type: Number,
      default: 1.5
    },
    renderOnlyOne: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      pages: [],
      id: Number(new Date()) + Math.random().toString(36).slice(-8)
    }
  },
  watch: {
    linkUrl: {
      immediate: true,
      handler: function (val) {
        if (val) {
          if (val) {
            this._loadFile(val)
          }
        }
      }
    }
  },
  methods: {
    _renderPage (num) {
      this.pdfDoc.getPage(num).then((page) => {
        const canvas = document.getElementById(this.id + '_canvas_' + num)
        const vp = page.getViewport({ scale: this.scale })
        const viewport = page.getViewport({ scale: window.innerWidth / vp.width })
        canvas.width = viewport.width
        canvas.height = viewport.height
        const ctx = canvas.getContext('2d')
        const renderContext = {
          canvasContext: ctx,
          transform: [1, 0, 0, 1, 0, 0],
          viewport: viewport,
          intent: 'print'
        }
        page.render(renderContext)
        if (!this.renderOnlyOne && this.pages > num) {
          this._renderPage(num + 1)
        }
      })
    },
    _loadFile (url) {
      PDFJS.getDocument(url).promise.then((pdf) => {
        this.pdfDoc = pdf
        this.pages = this.pdfDoc.numPages
        this.$nextTick(() => {
          this._renderPage(1)
          this.$emit('rendered')
        })
      }).catch(() => {
        this.$emit('rendered')
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
.container
  width 100%
  display flex
  flex-direction column
  .canvas
    margin 0 auto
</style>
